<?php
/************************************************************
 * Copyright (C), 1993, Dacelve. Tech., Ltd.
 * FileName : udp_setver.php
 * Author   : Lizhijian
 * Version  : 1.0
 * Date     : 2018/1/17 13:09
 * Description   :
 * Function List :
 * History  :
 * <author>    <time>    <version >    <desc>
 * Lizhijian   2018/1/17   1.0          init
 ***********************************************************/
require __DIR__.'/../application/ServerPack.php';
//$data = json_encode([
//    'cmd' => 'getPackList'
//]);
//$data = ServerPack::check($data);
//var_dump($data);die;

//创建Server对象，监听 127.0.0.1:9501端口
$serv = new swoole_server("120.24.219.140", 9501);

//监听连接进入事件
$serv->on('connect', function ($serv, $fd) {
    echo "Client: Connect.\n";
});

//监听数据接收事件
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    //检测数据包是否正确
    $data = ServerPack::check($data);
    if($data['code'] == ServerPack::OK_DATA_STATUS){
        switch ($data['data']['cmd']){
            //获取现有协议包
            case 'getPackList':
                $serv->send($fd, ServerPack::back(ServerPack::OK_DATA_MSG, ServerPack::getPackList()));
                break;

            //广播普通消息
            case 'msg':
                $startTime = time();
                $serv->tick(3000, function ($id) use ($serv, $data, $startTime) {
                    foreach ($serv->connections as $v) {
                        $serv->send($v, ServerPack::back(ServerPack::OK_DATA_MSG, $data['data']['msg']));
                    }
                    //N秒后公告停止
                    if(time() >= ($startTime + $data['data']['untilTime'])){
                        $serv->clearTimer($id);
                    }
                });
                break;
        }
    }else{
        $serv->send($fd, ServerPack::back(ServerPack::ERROR_DATA_MSG, $data['tip']));//错误包直接返回
    }



});

//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});

//启动服务器
$serv->start();
